package com.hhq.Dao.Impl;

import com.hhq.Dao.UserDao;
import com.hhq.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository

public class UserDaoImpl implements UserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    public List<User> getAllUser() {
        String sql = "select * from user";
        List<User> list = jdbcTemplate.query(sql,new BeanPropertyRowMapper<User>(User.class));
        return list;
    }

    @Override
    public List<User> findUserByName(String loginname) {
        String sql = "select * from user where loginname = ?";
        return jdbcTemplate.query(sql,new BeanPropertyRowMapper<User>(User.class), loginname);
    }

    public boolean checkAdminLogin(User user) {
        String sql = "select * from user where loginname=? and password=?";
        List<User> list = jdbcTemplate.query(sql,new BeanPropertyRowMapper<User>(User.class),
                new Object[]{user.getLoginname(),user.getPassword()});
        if (list.size()!=0)
            return true;
        return false;
    }

    @Override
    public int  addUser(User user) {
        String sql = "insert into user(loginname, password,username,createdate ) value(?,?,?,?)";
        int num = jdbcTemplate.update(sql,new Object[]{
                user.getLoginname(),
                user.getPassword(),
                user.getUsername(),
                user.getCreatedate()
        });
        return num;
    }

    @Override
    public void deleteUser(String loginname) {
        String sql = "delete from user where loginname=?";
        jdbcTemplate.update(sql,new Object[]{loginname});
    }

    @Override
    public int updateUser(User user) {
        String sql = "update user set username=?,password=? where loginname=?";
        Object[] objects = new Object[]{

                user.getUsername(),
                user.getPassword(),
                user.getLoginname()
        };
        int num = jdbcTemplate.update(sql,objects);
        return num;
    }

}
